package com.wushijia.controller;

import com.wushijia.model.User;
import com.wushijia.repository.UserRepository;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * description:在springboot中使用jsp时，不能使用@RestController, 而要使用@Controller
 *
 * @author yang
 * @date 2019/6/3 11:34
 */
@Controller
@RequestMapping("/home")
public class HomeController {

  @Autowired
  private UserRepository userRepository;

  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public ModelAndView login() {
    ModelAndView mv = new ModelAndView("redirect:/home/index");
    List<User> userList = (List<User>) userRepository.findAll();
    userList.forEach(user -> System.out.println(user.getUsername()));
    mv.addObject("message", "success");
    return mv;
  }

  @RequestMapping("/index")
  public String index() {
    return "index";
  }

  @ResponseBody
  @PostMapping(value = "/registeredUser")
  public Object registeredUser(@RequestParam String username) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    User user = new User();
    user.setId(String.valueOf(UUID.randomUUID()));
    user.setUsername(username);
    user.setPassword(encoder.encode("123456".trim()));
    userRepository.save(user);
    return "success";
  }

  @GetMapping("/user/{name}")
  public @ResponseBody
  User getUserByName(@PathVariable String name) {
    return userRepository.getUserByName(name);
  }

  @PutMapping("/updateUser/{name}")
  public @ResponseBody
  User updateUserByName(@RequestBody User user, @PathVariable String name) {
    user.setUsername(name);
    return user;
  }
}
